import React from 'react';
import { Layout, Menu, Avatar, Dropdown, Tooltip, ConfigProvider, theme } from 'antd';
import {
  HomeOutlined,
  AppstoreOutlined,
  UserOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  LogoutOutlined,
  KeyOutlined,
  DownOutlined,
  HddOutlined,
  ClusterOutlined,
  UnorderedListOutlined,
  EnvironmentOutlined,
  AlertOutlined,
  WalletOutlined,
  ProfileOutlined,
  ReconciliationOutlined,
  NotificationOutlined,
  SwapOutlined,
  ShoppingOutlined,
  ReloadOutlined,
  RiseOutlined,
  FallOutlined,
  ShoppingCartOutlined,
  TagsOutlined,
  TagOutlined,
  DatabaseOutlined,
  GiftOutlined,
  TeamOutlined,
  DesktopOutlined,
  LineChartOutlined,
  BarChartOutlined,
  AreaChartOutlined,
  PieChartOutlined,
  RollbackOutlined,
  PictureOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined,
  BulbOutlined,
  CustomerServiceOutlined,
  MailOutlined,
  SafetyCertificateOutlined,
  IdcardOutlined,
  AuditOutlined,
  MenuOutlined,
} from '@ant-design/icons';
import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom';
import logo from '../assets/logo.svg';

const { Header, Sider, Content } = Layout;

export default function AppLayout() {
  const location = useLocation();
  const navigate = useNavigate();
  const [collapsed, setCollapsed] = React.useState(false);
  const [openKeys, setOpenKeys] = React.useState([]);
  // 新增：全屏与夜间模式状态
  const [isFullscreen, setIsFullscreen] = React.useState(!!document.fullscreenElement);
  const [isDark, setIsDark] = React.useState(() => localStorage.getItem('theme') === 'dark');
  const BRAND = '#1296db';
  // 夜间模式持久化
  React.useEffect(() => {
    localStorage.setItem('theme', isDark ? 'dark' : 'light');
  }, [isDark]);
  // 监听全屏状态变化
  React.useEffect(() => {
    const handler = () => setIsFullscreen(!!document.fullscreenElement);
    document.addEventListener('fullscreenchange', handler);
    document.addEventListener('webkitfullscreenchange', handler);
    document.addEventListener('msfullscreenchange', handler);
    return () => {
      document.removeEventListener('fullscreenchange', handler);
      document.removeEventListener('webkitfullscreenchange', handler);
      document.removeEventListener('msfullscreenchange', handler);
    };
  }, []);
  // 切换主题
  const toggleTheme = React.useCallback(() => {
    setIsDark((v) => !v);
  }, []);
  // 切换全屏
  const toggleFullscreen = React.useCallback(() => {
    try {
      const docEl = document.documentElement;
      const request = docEl.requestFullscreen || docEl.webkitRequestFullscreen || docEl.msRequestFullscreen;
      const exit = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen;
      if (!document.fullscreenElement) {
        request && request.call(docEl);
      } else {
        exit && exit.call(document);
      }
    } catch (e) {}
  }, []);
  const { selectedKey, parentKey } = React.useMemo(() => {
    if (location.pathname.startsWith('/main')) return { selectedKey: 'main', parentKey: null };
    if (location.pathname.startsWith('/machine')) {
      if (location.pathname.startsWith('/machine/group')) return { selectedKey: 'machine-group', parentKey: 'device' };
      if (location.pathname.startsWith('/machine/list')) return { selectedKey: 'machine-list', parentKey: 'device' };
      if (location.pathname.startsWith('/machine/maps')) return { selectedKey: 'machine-maps', parentKey: 'device' };
      if (location.pathname.startsWith('/machine/alarm')) return { selectedKey: 'machine-alarm', parentKey: 'device' };
      return { selectedKey: 'machine-group', parentKey: 'device' }; // 默认选中机器组
    }
    if (location.pathname.startsWith('/promote')) {
      if (location.pathname.startsWith('/promote/config')) return { selectedKey: 'promote-config', parentKey: 'promote' };
      return { selectedKey: 'promote-config', parentKey: 'promote' };
    }
    if (location.pathname.startsWith('/wallet')) {
      if (location.pathname.startsWith('/wallet/account')) return { selectedKey: 'wallet-account', parentKey: 'wallet' };
      if (location.pathname.startsWith('/wallet/detail')) return { selectedKey: 'wallet-detail', parentKey: 'wallet' };
      if (location.pathname.startsWith('/wallet/record')) return { selectedKey: 'wallet-record', parentKey: 'wallet' };
      if (location.pathname.startsWith('/wallet/subscribe')) return { selectedKey: 'wallet-subscribe', parentKey: 'wallet' };
      if (location.pathname.startsWith('/wallet/topup')) return { selectedKey: 'wallet-topup', parentKey: 'wallet' };
      return { selectedKey: 'wallet-account', parentKey: 'wallet' };
    }
    if (location.pathname.startsWith('/product')) {
      if (location.pathname.startsWith('/product/type')) return { selectedKey: 'product-type', parentKey: 'product' };
      if (location.pathname.startsWith('/product/list')) return { selectedKey: 'product-list', parentKey: 'product' };
      if (location.pathname.startsWith('/product/tag')) return { selectedKey: 'product-tag', parentKey: 'product' };
      if (location.pathname.startsWith('/product/library')) return { selectedKey: 'product-library', parentKey: 'product' };
      if (location.pathname.startsWith('/product/coupons')) return { selectedKey: 'product-coupons', parentKey: 'product' };
      return { selectedKey: 'product-type', parentKey: 'product' };
    }
    if (location.pathname.startsWith('/order')) {
      if (location.pathname.startsWith('/order/list')) return { selectedKey: 'order-list', parentKey: 'order' };
      if (location.pathname.startsWith('/order/refund')) return { selectedKey: 'order-refund', parentKey: 'order' };
      if (location.pathname.startsWith('/order/recharge')) return { selectedKey: 'order-recharge', parentKey: 'order' };
      if (location.pathname.startsWith('/order/renewal')) return { selectedKey: 'order-renewal', parentKey: 'order' };
      if (location.pathname.startsWith('/order/withdrawal')) return { selectedKey: 'order-withdrawal', parentKey: 'order' };
      return { selectedKey: 'order-list', parentKey: 'order' };
    }
    if (location.pathname.startsWith('/adverts')) {
      if (location.pathname.startsWith('/adverts/gallery')) return { selectedKey: 'adverts-gallery', parentKey: 'adverts' };
      if (location.pathname.startsWith('/adverts/group')) return { selectedKey: 'adverts-group', parentKey: 'adverts' };
      if (location.pathname.startsWith('/adverts/machine-group')) return { selectedKey: 'adverts-machine-group', parentKey: 'adverts' };
      if (location.pathname.startsWith('/adverts/machine-label')) return { selectedKey: 'adverts-machine-label', parentKey: 'adverts' };
      return { selectedKey: 'adverts-gallery', parentKey: 'adverts' };
    }
    if (location.pathname.startsWith('/statistics')) {
      if (location.pathname.startsWith('/statistics/dateprofit')) return { selectedKey: 'statistics-date', parentKey: 'statistics' };
      if (location.pathname.startsWith('/statistics/adver')) return { selectedKey: 'statistics-adver', parentKey: 'statistics' };
      if (location.pathname.startsWith('/statistics/machineprofit')) return { selectedKey: 'statistics-machine', parentKey: 'statistics' };
      if (location.pathname.startsWith('/statistics/productprofit')) return { selectedKey: 'statistics-product', parentKey: 'statistics' };
      if (location.pathname.startsWith('/statistics/userprofit')) return { selectedKey: 'statistics-user', parentKey: 'statistics' };
      if (location.pathname.startsWith('/statistics/warn')) return { selectedKey: 'statistics-warn', parentKey: 'statistics' };
      return { selectedKey: 'statistics-date', parentKey: 'statistics' };
    }
    // 新增：帮助中心选中逻辑
    if (location.pathname.startsWith('/helpcenter')) {
      if (location.pathname.startsWith('/helpcenter/chat')) return { selectedKey: 'helpcenter-chat', parentKey: 'helpcenter' };
      return { selectedKey: 'helpcenter-chat', parentKey: 'helpcenter' };
    }
    // 新增：权限模块选中逻辑
    if (location.pathname.startsWith('/authority')) {
      if (location.pathname.startsWith('/authority/role')) return { selectedKey: 'authority-role', parentKey: 'authority' };
      if (location.pathname.startsWith('/authority/authorization')) return { selectedKey: 'authority-authorization', parentKey: 'authority' };
      if (location.pathname.startsWith('/authority/menu')) return { selectedKey: 'authority-menu', parentKey: 'authority' };
      if (location.pathname.startsWith('/authority/login')) return { selectedKey: 'authority-login', parentKey: 'authority' };
      if (location.pathname.startsWith('/authority/privacy')) return { selectedKey: 'authority-privacy', parentKey: 'authority' };
      if (location.pathname.startsWith('/authority/operation')) return { selectedKey: 'authority-operation', parentKey: 'authority' };
      return { selectedKey: 'authority-role', parentKey: 'authority' };
    }
    if (location.pathname.startsWith('/system')) {
      if (location.pathname.startsWith('/system/email')) return { selectedKey: 'system-email', parentKey: 'system' };
      if (location.pathname.startsWith('/system/app')) return { selectedKey: 'system-app', parentKey: 'system' };
      if (location.pathname.startsWith('/system/user')) return { selectedKey: 'system-user', parentKey: 'system' };
      if (location.pathname.startsWith('/system/certificate')) return { selectedKey: 'system-certificate', parentKey: 'system' };
      if (location.pathname.startsWith('/system/icard')) return { selectedKey: 'system-icard', parentKey: 'system' };
      if (location.pathname.startsWith('/system/idardlist')) return { selectedKey: 'system-idardlist', parentKey: 'system' };
      if (location.pathname.startsWith('/system/dictionary-data')) return { selectedKey: 'system-dictionary-data', parentKey: 'system' };
      return { selectedKey: 'system-email', parentKey: 'system' };
    }
    return { selectedKey: 'main', parentKey: null };
  }, [location.pathname]);

  React.useEffect(() => {
    if (!collapsed && parentKey) {
      setOpenKeys([parentKey]);
    } else {
      setOpenKeys([]);
    }
  }, [collapsed, parentKey]);

  const onOpenChange = (keys) => {
    setOpenKeys(keys);
  };

  const onMenuClick = ({ key }) => {
    if (key === 'password') {
      navigate('/password');
    } else if (key === 'logout') {
      localStorage.removeItem('isLoggedIn');
      localStorage.removeItem('menuList');
      navigate('/login', { replace: true });
    }
  };

  const userMenuItems = [
    { key: 'password', icon: <KeyOutlined />, label: '修改密码' },
    { type: 'divider' },
    { key: 'logout', icon: <LogoutOutlined />, label: '退出登录' },
  ];

    const menuItems = [
      { key: 'main', icon: <HomeOutlined />, label: <Link to="/main">首页</Link> },
      {
        key: 'device',
        icon: <HddOutlined />,
        label: '设备',
        children: [
          { key: 'machine-group', icon: <ClusterOutlined />, label: <Link to="/machine/group">机器组</Link> },
          { key: 'machine-list', icon: <UnorderedListOutlined />, label: <Link to="/machine/list">机器清单</Link> },
          { key: 'machine-maps', icon: <EnvironmentOutlined />, label: <Link to="/machine/maps">设备地图</Link> },
          { key: 'machine-alarm', icon: <AlertOutlined />, label: <Link to="/machine/alarm">告警记录</Link> },
        ],
      },
      {
        key: 'wallet',
        icon: <WalletOutlined />,
        label: '钱包',
        children: [
          { key: 'wallet-account', icon: <WalletOutlined />, label: <Link to="/wallet/account">我的钱包</Link> },
          { key: 'wallet-detail', icon: <ProfileOutlined />, label: <Link to="/wallet/detail">账单明细</Link> },
          { key: 'wallet-record', icon: <ReconciliationOutlined />, label: <Link to="/wallet/record">流水记录</Link> },
          { key: 'wallet-subscribe', icon: <NotificationOutlined />, label: <Link to="/wallet/subscribe">订阅管理</Link> },
          { key: 'wallet-topup', icon: <SwapOutlined />, label: <Link to="/wallet/topup">充值提现</Link> },
        ],
      },
      {
        key: 'order',
        icon: <ShoppingOutlined />,
        label: '订单管理',
        children: [
          { key: 'order-list', icon: <UnorderedListOutlined />, label: <Link to="/order/list">订单列表</Link> },
          { key: 'order-refund', icon: <RollbackOutlined />, label: <Link to="/order/refund">退款记录</Link> },
          { key: 'order-recharge', icon: <RiseOutlined />, label: <Link to="/order/recharge">充值记录</Link> },
          { key: 'order-renewal', icon: <ReloadOutlined />, label: <Link to="/order/renewal">续费记录</Link> },
          { key: 'order-withdrawal', icon: <FallOutlined />, label: <Link to="/order/withdrawal">提现记录</Link> },
        ],
      },
      {
        key: 'product',
        icon: <ShoppingCartOutlined />,
        label: '商品',
        children: [
          { key: 'product-type', icon: <TagsOutlined />, label: <Link to="/product/type">产品类型</Link> },
          { key: 'product-list', icon: <UnorderedListOutlined />, label: <Link to="/product/list">产品列表</Link> },
          { key: 'product-tag', icon: <TagOutlined />, label: <Link to="/product/tag">商品标签</Link> },
          { key: 'product-library', icon: <DatabaseOutlined />, label: <Link to="/product/library">主产品库</Link> },
          { key: 'product-coupons', icon: <GiftOutlined />, label: <Link to="/product/coupons">优惠券</Link> },
        ],
      },
      {
        key: 'adverts',
        icon: <NotificationOutlined />,
        label: '广告分组',
        children: [
          { key: 'adverts-gallery', icon: <PictureOutlined />, label: <Link to="/adverts/gallery">AD画廊</Link> },
          { key: 'adverts-group', icon: <TeamOutlined />, label: <Link to="/adverts/group">AD集团</Link> },
          { key: 'adverts-machine-group', icon: <DesktopOutlined />, label: <Link to="/adverts/machine-group">设备广告</Link> },
          { key: 'adverts-machine-label', icon: <TagsOutlined />, label: <Link to="/adverts/machine-label">标签广告</Link> },
        ],
      },
      {
        key: 'statistics',
        icon: <BarChartOutlined />,
        label: '统计',
        children: [
          { key: 'statistics-date', icon: <AreaChartOutlined />, label: <Link to="/statistics/dateprofit">日益统计</Link> },
          { key: 'statistics-adver', icon: <LineChartOutlined />, label: <Link to="/statistics/adver">广告统计</Link> },
          { key: 'statistics-machine', icon: <PieChartOutlined />, label: <Link to="/statistics/machineprofit">设备收益</Link> },
          { key: 'statistics-product', icon: <LineChartOutlined />, label: <Link to="/statistics/productprofit">商品收益</Link> },
          { key: 'statistics-user', icon: <LineChartOutlined />, label: <Link to="/statistics/userprofit">用户收益</Link> },
          { key: 'statistics-warn', icon: <AlertOutlined />, label: <Link to="/statistics/warn">告警统计</Link> },
        ],
      },
      {
        key: 'promote',
        icon: <RiseOutlined />,
        label: '推广',
        children: [
          { key: 'promote-config', icon: <ProfileOutlined />, label: <Link to="/promote/config">推广配置</Link> },
        ],
      },
      {
        key: 'authority',
        icon: <KeyOutlined />,
        label: '权限',
        children: [
          { key: 'authority-role', icon: <TeamOutlined />, label: <Link to="/authority/role">角色管理</Link> },
          { key: 'authority-authorization', icon: <KeyOutlined />, label: <Link to="/authority/authorization">授权管理</Link> },
          { key: 'authority-menu', icon: <MenuOutlined />, label: <Link to="/authority/menu">菜单管理</Link> },
          { key: 'authority-login', icon: <AuditOutlined />, label: <Link to="/authority/login">登录日志</Link> },
          { key: 'authority-privacy', icon: <AuditOutlined />, label: <Link to="/authority/privacy">隐私协议日志</Link> },
          { key: 'authority-operation', icon: <AuditOutlined />, label: <Link to="/authority/operation">操作日志</Link> },
        ],
      },
      {
        key: 'helpcenter',
        icon: <CustomerServiceOutlined />,
        label: '帮助中心',
        children: [
          { key: 'helpcenter-chat', icon: <CustomerServiceOutlined />, label: <Link to="/helpcenter/chat">客服聊天</Link> },
        ],
      },
      {
        key: 'system',
        icon: <AppstoreOutlined />,
        label: '系统',
        children: [
          { key: 'system-email', icon: <MailOutlined />, label: <Link to="/system/email">邮箱配置</Link> },
          { key: 'system-app', icon: <AppstoreOutlined />, label: <Link to="/system/app">App版本</Link> },
          { key: 'system-user', icon: <UserOutlined />, label: <Link to="/system/user">用户管理</Link> },
          { key: 'system-certificate', icon: <SafetyCertificateOutlined />, label: <Link to="/system/certificate">凭证管理</Link> },
          { key: 'system-icard', icon: <IdcardOutlined />, label: <Link to="/system/icard">IC卡管理</Link> },
          { key: 'system-idardlist', icon: <ProfileOutlined />, label: <Link to="/system/idardlist">证件列表</Link> },
          { key: 'system-dictionary-data', icon: <DatabaseOutlined />, label: <Link to="/system/dictionary-data">字典数据</Link> },
        ],
      },
    ];

  return (
    <ConfigProvider theme={{ algorithm: isDark ? theme.darkAlgorithm : theme.defaultAlgorithm, token: { colorPrimary: BRAND } }}>
      <Layout style={{ minHeight: '100vh' }}>
        <Sider width={220} theme="dark" collapsible collapsed={collapsed} trigger={null} collapsedWidth={60}>
          <div style={{
            height: 60,
            display: 'flex',
            alignItems: 'center',
            justifyContent: collapsed ? 'center' : 'flex-start',
            paddingLeft: collapsed ? 0 : 16,
            gap: 8,
            color: '#fff',
            fontWeight: 600
          }}>
            <img src={logo} alt="Logo" style={{ width: 28, height: 28 }} />
            {!collapsed && <span>设备管理系统</span>}
          </div>
          <Menu
            theme="dark"
            mode="inline"
            items={menuItems}
            selectedKeys={[selectedKey]}
            openKeys={openKeys}
            onOpenChange={onOpenChange}
            style={{ height: 'calc(100% - 60px)' }}
          />
        </Sider>
        <Layout>
          <Header
            style={{
              height: 60,
              display: 'flex',
              alignItems: 'center',
              padding: '0 16px',
              background: '#001529',
              position: 'sticky',
              top: 0,
              zIndex: 10,
              boxShadow: '0 2px 8px rgba(0,0,0,0.15)'
            }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <span onClick={() => setCollapsed((c) => !c)} style={{ color: '#fff', cursor: 'pointer', fontSize: 18 }}>
                {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              </span>
            </div>
            <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 12 }}>
              {/* 夜间模式切换按钮 */}
              <Tooltip title={isDark ? '切换为日间模式' : '切换为夜间模式'}>
                <button type="button" onClick={toggleTheme} className="icon-btn" aria-label={isDark ? '切换为日间模式' : '切换为夜间模式'}>
                  <BulbOutlined />
                </button>
              </Tooltip>
              {/* 全屏切换按钮 */}
              <Tooltip title={isFullscreen ? '退出全屏' : '全屏'}>
                <button type="button" onClick={toggleFullscreen} className="icon-btn" aria-label={isFullscreen ? '退出全屏' : '全屏'}>
                  {isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
                </button>
              </Tooltip>
              {/* 用户下拉 */}
              <Dropdown menu={{ items: userMenuItems, onClick: onMenuClick }} placement="bottomRight" trigger={["click"]}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', color: '#fff' }}>
                  <Avatar size={28} icon={<UserOutlined />} />
                  <span>Admin</span>
                  <DownOutlined />
                </div>
              </Dropdown>
            </div>
          </Header>
          <Content style={{ padding: 16, background: isDark ? '#141414' : '#f0f2f5' }}>
            <Outlet />
          </Content>
        </Layout>
      </Layout>
    </ConfigProvider>
  );
}